package com.srini.listeners;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.srini.util.ConnectionUtil;
import com.vssr.persist.util.DBResourceUtil;


/**
 * Application Lifecycle Listener implementation class ContextListener
 * 
 */
public class ContextListener implements ServletContextListener {

	/**
	 * Default constructor.
	 */
	public ContextListener() {
	}

	/**
	 * @see ServletContextListener#contextInitialized(ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("Context Initialized");
		Connection con = null;
		try {
			System.out.println("Initializing application....");
			con = new ConnectionUtil().getConnection();
			if (con.getMetaData().getTables(null, "TRMS", "USERTABLE", null)
					.next() == false) {
				System.out.print("Running initial scripts... ");
				InputStream is = getClass().getResourceAsStream("/scripts.sql");
				BufferedReader r = new BufferedReader(new InputStreamReader(is));
				DBResourceUtil.runScript(r, con);
				System.out.println("DONE.");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			/*try {
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}*/
		}
	}

	/**
	 * @see ServletContextListener#contextDestroyed(ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("Performing closing activities...");
		System.out.println("Context Destroyed...");
		new ConnectionUtil().closeConnection();
	}

}
